import pandas as pd
df = pd.read_csv('merge.csv')
df['create_time'] = pd.to_datetime(df['create_time'])
df['年份'] = df['create_time'].dt.year
df['月份'] = df['create_time'].dt.month
df['季度'] = (df['月份'] - 1) // 3 + 1
total_sales = df.groupby(['年份', 'hplx', 'cppp'])['jz'].sum().reset_index()
top_customers_by_month_product_type = {}
for (year,product_type), group in total_sales.groupby(['年份', 'hplx']):
    # 对品牌购买量进行排序，并取出前五名
    top_brands = group.groupby('hplx')['jz'].sum().sort_values(ascending=False).head(3)
    # 筛选出这些品牌的数据，并对客户购买量进行排序
    top_customers = group[group['hplx'].isin(top_brands.index)].sort_values(by=['hplx', 'jz'],
                                                                                ascending=[True, False])
    # 由于可能存在多个客户购买同一品牌的产品，我们需要对每个品牌再取前五名客户
    top_customers_per_brand = []
    for brand, brand_group in top_customers.groupby('hplx'):
        top_customers_per_brand.append(brand_group.head(3))
        # 合并所有品牌的前五名客户数据
    top_customers_by_month_product_type[(year, product_type)] = pd.concat(top_customers_per_brand)

# 准备将结果写入CSV文件
results = pd.concat(top_customers_by_month_product_type.values(), ignore_index=True)

# 写入CSV文件
results.to_csv('top_customers_by_month_product_type.csv', index=False)

